
<template>
    <div class="car flexv">
        <!-- 头部 -->
        <div class="heads">
            <div class="tips tc">购物车</div>
            <div class="charge tc" @click="changeType" v-if="!charge && !isNone">管理</div>
            <div class="charge tc on" @click="changeType" v-if="charge && !isNone">完成</div>
        </div>

        <!-- 列表 -->
        <div class="car_lists flexv">
            <van-list :finished="finished" @load="getData" v-model="loading">
                <div class="car_list flexv">
                    <!-- 商品信息 -->
                    <div class="goods_infos" v-for="(goods,ind) in list" :key="ind">
                        <!-- 选择框 -->
						<div class="flex goods-title ali-c">
							<img src="@/assets/e_shop@2x.png" />
							{{goods.merchant_name}}
						</div>
						<div class="flex mt2" v-for="(item,index) in goods.goods" :key="index">
							<img src="@/assets/checked.png" class="check" v-if="item.check" @click="chooseGoods(ind,index)" alt="">
							<img src="@/assets/check.png" class="check" v-else alt="" @click="chooseGoods(ind,index)">
							<!-- 商品图片 -->
							<div class="goods_img flex">
							    <img :src="item.image" @click="toDetail(item.goods_id)" alt="">
							</div>
							
							<div class="flex1 flexv goods_info jus-b"  @click="toDetail(item.goods_id)">
							    <p class="twoline title">{{item.goods_name}}</p>
							    <span class="spec" v-if="item.key_name">{{item.key_name}}</span>
							
							    <div class="fix jus-b">
							        <span class="price">￥{{item.goods_price}}</span>
							
							        <div class="action_btn flex">
							            <div class="act_cut tc" @click.stop="cutNum(item.id,ind,index)">-</div>
							            <div class="act_num tc flex1">{{item.num}}</div>
							            <div class="act_add tc" @click.stop="addNum(item.id,ind,index)">+</div>
							        </div>
							    </div>
							</div>
						</div>
						
                    </div>
                </div>
            </van-list>
        </div>

        <!-- 空购物车 -->
        <div class="empty_box flexv flexc" v-if="isNone">
            <img src="@/assets/nocar.png" alt="">
            <div class="btn white tc" @click="toLook">去逛逛</div>
        </div>

        <!-- 当季热卖 -->
        <div class="hot_title flexc" v-if="isNone">
            <img src="@/assets/a_best_sellers.png" alt="">
        </div>
        <!-- 热卖商品 -->
        <van-list v-model="loading" finished="finished" @load="getItems">
            <div class="goods_lists flex-wrap" v-if="isNone">
                <div class="goods-list flexv" @click="toxDetail(item.goods_id)" v-for="(item,index) in item_list" :key="index">
                    <div class="goods-img flex">
                        <img v-lazy="item.image" :src="item.image" class="goods_img" alt="" >
                    </div>
                    <div class="goods-info flexv jus-b flex1">
                        <p class="twoline title">{{item.goods_name}}</p>
                        <div class="goods-fix jus-b ali-c">
                            <span>￥{{item.goods_price}}</span>
                            <span class="sales tc" v-if="item.return_price>=0">分享赚￥{{item.return_price}}</span>
                        </div>
                    </div>
                </div>
            </div>
        </van-list>

        <!-- 购物车底部 -->
        <div class="actions" v-if="!isNone">
            <div class="actions_btns flex">
                <div class="left_btn flex1 jus-b">
                    <div class="flex ali-c" @click="selectAll">
                        <img src="@/assets/checked.png" v-if="chooseAll" alt="">
                        <img src="@/assets/check.png" alt="" v-else>
                        <span>全选</span>
                    </div>

                    <div class="notice ali-b" v-if="!charge && !isNone">
                        <span>合计:</span>
                        <span class="price">￥{{totalPrice ? totalPrice : '0.00'}}</span>
                    </div>
                </div>

                <div class="right_btns flex">
                    <div class="flex1 white tc green" v-if="!charge" @click="toBuy">结算</div>
                    <div class="flex1 white tc" v-if="charge && ids.length < 1">删除</div>
                    <div class="flex1 white tc on" @click="delAct" v-if="charge && ids.length > 0">删除</div>
                </div>
            </div>
        </div>

        <pubFoot index="car" :cartNumber="cartNumber"></pubFoot>
    </div>
</template>
<script>
import Vue from 'vue';
import pubFoot from '@/components/foot';
import { Toast, Dialog, List } from 'vant';
import { cart, cartDel, cartEdit, cartNums, hotlist } from '@/request/api';

Vue.use(Toast, Dialog, List)
export default {
    data (){
        return{
            cartNumber: 0, // 购物车数量
            once: true, // 复制重复提交
            isNone: false, // 是否为空
            chooseAll: false, // 是否全选
            charge: false, // 是否是删除按钮
            ids: [], // 选择的购物车id
            // 列表相关
            list: [], // 购物车列表
            page: 0,
            pagea: 0,
            pagesize: 10,
            finished: false,
            loading: false,
            totalPrice: 0.00, // 总价
            subItem: [], // 要提交的商品信息
            loadNew: true,
            item_list: [], // 推荐列表
        }
    },
    created(){
        this.$loading()
        if(localStorage.getItem('cartNums')){
            this.cartNumber = Number(localStorage.getItem('cartNums'));
        }
    },
    components: {
        pubFoot,
        "van-list":List,
    },
    methods: {
        // 获取数据
        getData(){
            this.loading = true;
            cart({
                token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
                page: ++this.page,
                pagesize: this.pagesize
            }).then(res =>{
                Toast.clear();
                this.loading = false;
                if(res.code == 1){
                    this.finished = Number(res.data.cart_list.length) >= Number(this.pagesize) ? false : true;
                    if(res.data.cart_list.length > 0){
                        res.data.cart_list.forEach((item) =>{
                            // item.check = false;
							item.goods.forEach((child)=>{
								child.check = false;
								child.merchant_name = item.merchant_name;
							})
                        })
                        this.list = [...this.list,...res.data.cart_list];
                    }

                    if(this.list.length < 1){
                        this.isNone = true;
                        this.getItems();
                    }else{
                        this.isNone = false
                    }
                }else{
					this.finished = true;
                    this.isNone = true;
					if(res.msg == '请登录后操作'){
						this.$tip('您的登录已失效,即将重新登录!');
						setTimeout(()=>{
							localStorage.clear();
							// sessionStorage.clear();
							window.location.href = 'http://mbgo.0791jr.com';
						},1200)
					}
                }
            })
			
        },
		getData_1(){
		    this.loading = true;
		    cart({
		        token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
		        page: 1,
		        pagesize: this.pagesize
		    }).then(res =>{
		        Toast.clear();
		        this.loading = false;
		        if(res.code == 1){
					this.list = []
		            this.finished = Number(res.data.cart_list.length) >= Number(this.pagesize) ? false : true;
		            if(res.data.cart_list.length > 0){
		                res.data.cart_list.forEach((item) =>{
		                    item.check = false;
		                })
		                this.list = [...this.list,...res.data.cart_list];
		            }
					
		            if(this.list.length < 1){
		                this.isNone = true;
		                this.getItems();
		            }else{
		                this.isNone = false
		            }
		        }else{
					this.finished = true;
		            this.isNone = true;
					if(res.msg == '请登录后操作'){
						this.$tip('您的登录已失效,即将重新登录!');
						setTimeout(()=>{
							localStorage.clear();
							// sessionStorage.clear();
							window.location.href = 'http://mbgo.0791jr.com';
						},1200)
					}
		        }
		    })
			
		},
        // 获取当季热卖
        getItems(){
            hotlist({
                token: localStorage.getItem('token'),
                page: ++this.pagea,
                pagesize: this.pagesize
            }).then(res => {
                Toast.clear();
                if(res.code == 1){
                    this.finished = Number(res.data.hot_item) >= Number(this.pagesize) ? false : true;
                    if(res.data.hot_item.length > 0){
                        this.item_list = [...this.item_list,...res.data.hot_item];
                    }
                }
            })
        },
        // 获取购物车商品数量
        getNums(){
            // cartNums({
            //     token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
            // }).then(res =>{
            //     if(res.code == 1){
            //         if(this.cartNumber != res.data.num){
            //             this.cartNumber = res.data.num;
            //             localStorage.setItem('cartNums',res.data.num)
            //         }
            //     }
            // })
        },
        // 去逛逛
        toLook(){
            this.$router.replace('/classify')
        },
        // 改变管理状态
        changeType(){
            this.charge = !this.charge
        },
        // 去商品详情
        toDetail(id){
            this.$router.push('/goodsDetail?id='+id)
        },
        // 选择商品
        chooseGoods(father,index){
            // 改变当前商品的选择状态
			this.list[father].goods[index].check = !this.list[father].goods[index].check
            // 查看当前商品所在店铺是否满足店铺全选
            let goodsArr = [];
            this.list.map((item) =>{
				item.goods.forEach(child=>{
					if(child.check){
					    goodsArr.push(item)
					}
				})
				
               
            })
            // if(goodsArr.length == this.list[father].length){
            //     this.list[father].check = true;
            // }else{
            //     this.list[father].check = false;
            // }
            // 检查是否购物车满足全选
            this.checkCarAll();
             // 计算价格
            this.sumPrice();
        },
        // 全选
        selectAll(){
            this.chooseAll = !this.chooseAll;
            this.list.map((item) =>{
                // if(this.chooseAll){
                //     item.check = true
                // }else{
                //     item.check = false
                // }
                item.goods.forEach((x) =>{
                    if(this.chooseAll){
                        x.check = true
                    }else{
                        x.check = false
                    }
                })
            })

            // 获取选中商品的购物车id
            this.getSelectIds();
            // 计算价格
            this.sumPrice();
        },
        // 计算价格
        sumPrice(){
            let price = 0;
            this.list.map((item) =>{
               item.goods.map((child=>{
				   if(child.check){
				       price = (Number(price) + Number(child.goods_price * child.num)).toFixed(2);
				   }
			   }))
				
            })
            this.totalPrice = price;
        },
        // 检查是否满足购物车全选
        checkCarAll(){
            let carArr = [];
			let list = [];
            this.ids = [];
            this.list.map((item) =>{
				item.goods.map(child=>{
					if(child.check){
						carArr.push(child)
					}
					list.push(child)
				})
				
				
                // if(item.check){
                //     carArr.push(item);
                // }
            })
			
            if(carArr.length == list.length){
                this.chooseAll = true;
            }else{
                this.chooseAll = false;
            }
            this.getSelectIds();
        },
        // 删除
        delAct(){
            Dialog.confirm({
                title: '确定要删除所选商品吗？',
                confirmButtonText: '确定删除',
                confirmButtonColor: '#ff4400',
            }).then(res =>{
                this.$loading();
                cartDel({
                    token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
                    ids: this.ids.join(',')
                }).then(res =>{
                    Toast.clear();
                    if(res.code == 1){
                        this.getData_1();
                        // this.getNums();
                    }
                })
            }).catch(err =>{

            })
        },
        // 结算
        toBuy(){
            if(this.ids.length < 1){
                this.$tip('请选择要结算的商品!');
                return
            }
            this.$router.push('/placeholder_1?data='+JSON.stringify(this.subItem))
        },
        // 去虚拟商品详情
        toxDetail(id){
            this.$router.push('/detail?id='+id + '&type=1')
        },
        // 获取选中商品的购物车id
        getSelectIds(){
            this.ids = [];
			this.subItem = []
			let newList = [];
            this.list.forEach((item) =>{
				item.goods.forEach((child)=>{
					if(child.check){
						newList.push(item)
						this.subItem.push(item)
					    this.ids.push(child.id)
					}
				})
            })
			// ab.forEach((item2,index) =>{
			// 	item2.goods.forEach((x,ind) =>{
			// 		if(!x.check){
			// 			item2.goods.splice(ind,1);
			// 		}
					
			// 	})
			// })
        },
        // 增加数量
        addNum(id,father,index){
			this.$loading()
            if(this.once){
                this.once = false;
                cartEdit({
					type:1,
                    id: id,
                    num: 1,
                    token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
                }).then(res =>{
                    this.once = true;
                    if(res.code == 1){
						Toast.clear()
						this.list[father].goods[index].num++
                        this.sumPrice();
						
                    }
                })
            }
        },
        // 减少数量
        cutNum(id,father,index){
			this.$loading()
            if(this.once){
                this.once = false;
                if(this.list[father].goods[index].num == 1){
                    this.$tip('不能再减了哦T_T');
                    this.once = true;
                    return
                }
                cartEdit({
                    type:1,
                    id: id,
                    num: -1,
                    token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
                }).then(res =>{
                    this.once = true;
                    if(res.code == 1){
						Toast.clear()
						this.list[father].goods[index].num--
                        this.sumPrice();
						
                    }
                })
            }
        },
    }
}
</script>
<style lang="less" scoped>
.footer{
    margin-top: 0.2rem;
}
.car{
    min-height: 100vh;
    background-color: #f5f5f5;
    // 头部
    .heads{
        width: 100%;
        height: 0.88rem;
        .tips{
            width: 100%;
            max-width: 750px;
            height: 0.88rem;
            margin: 0 auto;
            position: fixed;
            z-index: 100;
            top: 0;
            left: 0;
            right: 0;
            border-bottom: 1px solid #efefef;
            font-size: 0.34rem;
            line-height: 0.88rem;
            color: #333;
            background-color: #fff;
        }
        .charge{
            width: 0.88rem;
            height: 0.88rem;
            position: fixed;
            z-index: 110;
            top: 0;
            right: 0;
            font-size: 0.3rem;
            line-height: 0.88rem;
            color: #666;
        }
        .on{
            color: #FF4400;
        }
    }
    // 商品列表
    .car_lists{
        padding: 0 0.3rem;
        .car_list{
            // padding: 0.28rem 0.24rem;
            border-radius: 0.1rem;
            // background-color: #fff;
            // 店铺信息
            .store_infos{
                height: 0.4rem;
                font-size: 0.32rem;
                line-height: 0.4rem;
                font-weight: bold;
                color: #333;
                .check{
                    width: 0.38rem;
                    height: 0.38rem;
                    margin: auto 0;
                    border-radius: 100%;
                }
                .to_ico{
                    width: 0.12rem;
                    height: 0.2rem;
                    margin: auto 0 auto 0.16rem;
                }
            }
            // 商品信息
            .goods_infos{
                margin-top: 0.2rem;
				padding: 0.3rem;
				background-color: #fff;
				.goods-title{
					color: #333;
					font-size: 0.32rem;
					margin-bottom: 0.3rem;
					img{
						width: 0.36rem;
						height: 0.32rem;
						margin-right: 0.1rem;
					}
				}
                // 选择框
                .check{
                    width: 0.38rem;
                    height: 0.38rem;
                    border-radius: 100%;
                    margin: auto 0;
                }
                .goods_img{
                    width: 1.8rem;
                    height: 1.8rem;
                    margin-left: 0.28rem;
                    border-radius: 0.1rem;
                    border: 1px solid #f5f5f5;
                    overflow: hidden;
                    img{
                        margin: auto;
                    }
                }
                .goods_info{
                    margin-left: 0.2rem;
                    padding: 0.04rem 0;
                    .title{
                        font-size: 0.28rem;
                        line-height: 150%;
                        color: #333;
                    }
                    .spec{
                        margin-right: auto;
                        font-size: 0.2rem;
                        line-height: 120%;
                        color: #666;
                    }
                    .fix{
                        .price{
                            margin-top: auto;
                            font-size: 0.28rem;
                            line-height: 120%;
                            color: #ff4400;
                        }
                        .action_btn{
                            width: 1.6rem;
                            height: 0.46rem;
                            border: 1px solid #e5e5e5;
                            border-radius: 0.06rem;
                            .act_cut,.act_add{
                                width: 0.46rem;
                                font-size: 0.4rem;
                                line-height: calc(0.46rem - 2px);
                                color: #aaa;
                            }
                            .act_cut{
                                font-size: 0.5rem;
                            }
                            .act_num{
                                font-size: 0.28rem;
                                line-height: 0.44rem;
                                color: #666;
                                border-left: 0.01rem solid #e5e5e5;
                                border-right: 0.01rem solid #e5e5e5;
                            }
                        }
                    }
                }
            }
        }
    }
    // 空
    .empty_box{
        font-size: 0.3rem;
        background-color: #fff;
        img{
            width: 3.24rem;
            height: 3.88rem;
            margin: 0.4rem auto 0;
        }
        .btn{
            width: 2rem;
            height: 0.6rem;
            margin-top: 0.3rem;
            margin-bottom: 0.7rem;
            line-height: 0.6rem;
            border-radius: 0.3rem;
            background-color: #50AD22;
        }
    }
    // 当季热卖
    .hot_title{
        height: 0.88rem;
        img{
            height: 0.48rem;
            margin: auto;
        }
    }
    // 热卖商品
    .goods_lists{
        margin-top: 0.2rem;
        padding: 0 0.28rem;
        .goods-list{
            width: calc((100% - 0.2rem) / 2);
            margin: 0 0.2rem 0.2rem 0;
            padding: 0.2rem 0.2rem 0.3rem;
            border-radius: 0.1rem;
            background-color: #fff;
            .goods-img{
                width: 2.9rem;
                height: 2.9rem;
                margin: 0 auto;
                border-radius: 0.1rem;
                border: 0.01rem solid #f5f5f5;
                overflow: hidden;
                .goods_img{
                    margin: auto;
                }
            }
            .goods-info{
                margin-top: 0.2rem;
                font-size: 0.28rem;
                line-height: 120%;
                color: #333;
                .title{
                    line-height: 150%;
                }
                .goods-fix{
                    margin-top: 0.2rem;
                    font-size: 0.34rem;
                    color: #EE1C1A;
                    .sales{
                        width: 1.3rem;
                        height: 0.4rem;
                        font-size: 0.2rem;
                        line-height: 0.4rem;
                        color: #EE1C1A;
                        border-radius: 0.1rem;
                        background-color: #FFF6F6;
                    }
                    img{
                        width: 0.46rem;
                        height: 0.46rem;
                        margin: auto 0;
                        border-radius: 100%;
                    }
                }
            }
        }
        .goods-list:nth-child(2n){
            margin-right: 0;
        }
    }
    // 购物车底部
    .actions{
        width: 100%;
        height: 0.98rem;
        .actions_btns{
            width: 100%;
            max-width: 750px;
            height: 0.98rem;
            margin: 0 auto;
            position: fixed;
            z-index: 101;
            bottom: 0.98rem;
            left: 0;
            right: 0;
            font-size: 0.3rem;
            box-shadow: 0 -0.04rem 0.04rem 0 #efefef;
            border-bottom: 0.01rem solid #eaeaea;
            background-color: #fff;
            .left_btn{
                margin: auto 0 auto 0.3rem;
                img{
                    width: 0.4rem;
                    height: 0.4rem;
                    border-radius: 100%;
                }
                span{
                    margin-left: 0.1rem;
                    line-height: 120%;
                }
                .notice{
                    font-size: 0.28rem;
                    line-height: 120%;
                    color: #333;
                    .price{
                        font-size: 0.36rem;
                        color: #FF4400FF;
                    }
                }
            }
            // 操作按钮
            .right_btns{
                width: 2rem;
                height: 100%;
                margin-left: 0.3rem;
                font-size: 0.3rem;
                line-height: 0.98rem;
                div{
                    background-color: #BEBEBE;
                }
                .on{
                    background-color: #FEA382;
                }
				.green{
					background-color: #50AD22;
				}
            }
        }
    }
}
</style>